package cn.edu.sctu.sctu_lysd.view.act;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.List;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.adapter.IndexListViewAda;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.bean.ParcelData;
import cn.edu.sctu.sctu_lysd.biz.IndexBiz;
import cn.edu.sctu.sctu_lysd.cofig.CacheKeyConfig;
import cn.edu.sctu.sctu_lysd.databinding.ActivityMainBinding;
import cn.edu.sctu.sctu_lysd.my_view.SlidingMenu;
import cn.edu.sctu.sctu_lysd.my_view.XListView;
import cn.edu.sctu.sctu_lysd.presenter.IndexPresenter;
import cn.edu.sctu.sctu_lysd.utils.JumpUtils;
import cn.edu.sctu.sctu_lysd.utils.ProgressUtil;
import cn.edu.sctu.sctu_lysd.utils.SharePreferenceUtils;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

public class IndexActivity extends BaseActivity implements IndexBiz.IndexBizView, RongIM.UserInfoProvider{

    private ActivityMainBinding mBinding;
    private IndexBiz.Presenter mPresenter;

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    private SharePreferenceUtils sharePreferenceUtils;

    private XListView mListView;

    private int nowPage = 1;
    private int pageSize = 10;
    private IndexListViewAda indexListViewAda;

    /**
     * intent 数据 key
     */
    public final static String ORIGIN_PRE = "originPre";
    public final static String ORIGIN_DETAIL = "originDetail";

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_main;
    }

    @Override
    protected void initBefore() {
        super.initBefore();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    @Override
    protected void initAfter(Object bind) {

        mBinding = (ActivityMainBinding) bind;
        sharePreferenceUtils = SharePreferenceUtils.getInstance(this);

        /**
         * 设置 用户信息
         */
        RongIM.setUserInfoProvider(this,true);

        mBinding.idMenu.setStateChangedListener(new SlidingMenu.StateChangedListener() {
            @Override
            public void menuDisplay() {

                if (sharePreferenceUtils.ifHaveShare(CacheKeyConfig.CACHE_USER_AVATAR_URL)) {

                    loadAvatarUrl(mBinding.include.menuUserPhoto);
                    mBinding.include.idMeUsername.setText(sharePreferenceUtils.getString(CacheKeyConfig.CACHE_USER_NICKNAME));

                }
                mBinding.overlayLin.setVisibility(View.VISIBLE);
                mBinding.overlayLin.setClickable(true);
                mBinding.overlayLin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBinding.idMenu.closeMenu();
                    }
                });
            }

            @Override
            public void menuHide() {
                loadAvatarUrl(mBinding.idIndexUserPhoto);
                mBinding.overlayLin.setClickable(false);
                mBinding.overlayLin.setVisibility(View.GONE);
            }
        });

        setEvent();
        mListView = mBinding.indexListView;
    }

    private void setEvent() {
        mBinding.originPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.showPlacePupWin(mBinding.choiceDemand);
            }
        });

        mBinding.choiceDemand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.showDemandWin(mBinding.moreIcon);
            }
        });

    }

    public void toggleMenu(View view) {

        mBinding.idMenu.toggle();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initPresenter(new IndexPresenter(this, this));

        mPresenter.isLogin();

        mBinding.idMenu.closeMenu();
    }

    @Override
    public void initPresenter(IndexBiz.Presenter presenter) {
        mPresenter = presenter;
        mPresenter.start();
        mPresenter.getParcels(nowPage, pageSize);
    }


    @Override
    public void alreadyLogin() {

        mBinding.include.idMeUsername.setText(sharePreferenceUtils.getString(CacheKeyConfig.CACHE_USER_NICKNAME));
        mBinding.include.idMeUsernameBottomText.setText("善意出行，善意接单");
        loadAvatarUrl(mBinding.idIndexUserPhoto);

        mBinding.include.idMeTwoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndexActivity.this, MyOrdersActivity.class);

                startActivity(intent);
            }
        });

        mBinding.include.idMeFourBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 退出登陆
                 */

                ProgressUtil.showAlertDialog("是否注销", "您确定注销登陆吗？",
                        IndexActivity.this, new ProgressUtil.AlertDialogCallBack() {
                            @Override
                            public void submit() {
                                mPresenter.logOut();
                                JumpUtils.jumpActivity(IndexActivity.this, LoginAct.class);
                            }

                            @Override
                            public void cancel() {

                            }
                        });


            }
        });

        mBinding.include.idMeThreeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                JumpUtils.jumpActivity(IndexActivity.this, DepositAct.class);

            }
        });

        mBinding.include.idMeOneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JumpUtils.jumpActivity(IndexActivity.this,UpdateUserInfoAct.class);
            }
        });

        mBinding.messageIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                /**
                 * 开启聊天人列表
                 */

                if (RongIM.getInstance() != null)
                    RongIM.getInstance().startConversationList(IndexActivity.this);
            }
        });


    }

    @Override
    public void notLogin() {

        mBinding.include.idMeUsername.setText("点击头像登陆");
        mBinding.include.idMeUsernameBottomText.setText("");
        mBinding.include.menuUserPhoto.setImageResource(R.mipmap.user_default_portrait);

        mBinding.include.menuUserPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.intentToLogin();
            }
        });

        mBinding.idIndexUserPhoto.setImageResource(R.mipmap.user_default_portrait);

        mBinding.include.idMeOneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.intentToLogin();
            }
        });
        mBinding.include.idMeTwoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.intentToLogin();

            }
        });
        mBinding.include.idMeThreeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.intentToLogin();
            }
        });
        mBinding.include.idMeFourBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.intentToLogin();
            }
        });

        mBinding.originPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });


    }

    @Override
    public void selectPlaceOver(String place) {
        mBinding.originPre.setText(place);
    }

    @Override
    public String getOriginPre() {
        return mBinding.originPre.getText().toString();
    }

    @Override
    public String getOriginDetail() {
        return mBinding.originDetail.getText().toString();
    }

    @Override
    public void loadAvatarUrl(ImageView view) {

        if (sharePreferenceUtils.ifHaveShare(CacheKeyConfig.CACHE_USER_AVATAR_URL)) {

            Picasso.with(this)
                    .load(sharePreferenceUtils.getString(CacheKeyConfig.CACHE_USER_AVATAR_URL))
                    .into(view);
        }

    }

    @Override
    public void getParcelsSuccess(List<ParcelData> data, int page) {

        if (data == null || data.size() == 0){//没有更多数据

            mListView.stopRefresh();
            mListView.stopLoadMore();
            return;
        }

        nowPage++;

        if (page == 1) {

            if (indexListViewAda == null) {//第一次进入页面

                indexListViewAda = new IndexListViewAda(this, data);

                mListView.setAdapter(indexListViewAda);
            }else {//刷新进入

                indexListViewAda.refresh(data);

            }

            mListView.setPullLoadEnable(true);//开启上拉加载

            mListView.setPullRefreshEnable(true);

            mListView.stopRefresh();

            mListView.setXListViewListener(new XListView.IXListViewListener() {
                @Override
                public void onRefresh() {

                    nowPage = 1;

                    mPresenter.getParcels(nowPage, pageSize);
                }

                @Override
                public void onLoadMore() {

                    mPresenter.getParcels(nowPage, pageSize);

                }
            });

        } else {//加载更多

            mListView.stopLoadMore();//数据获取成功  停止加载

            indexListViewAda.loadMore(data);

        }

    }

    @Override
    public void getParcelsFailed(int page) {

        Toast.makeText(this,"网络错误",Toast.LENGTH_SHORT).show();

    }


    @Override
    public void onClick(View v) {


    }


    /**
     * 按2次退出
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "您真的忍心离开吗？",
                    Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            appManager.exit();
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public UserInfo getUserInfo(String s) {

      SharePreferenceUtils sharePreferenceUtils =  SharePreferenceUtils.getInstance(this);

        return new UserInfo(s,
                sharePreferenceUtils.getString(CacheKeyConfig.CACHE_USER_NICKNAME),
                Uri.parse(sharePreferenceUtils.getString(CacheKeyConfig.CACHE_USER_AVATAR_URL)));
    }
}
